package fun.codedesign.principle.advice151.a100;

import java.lang.reflect.Array;
import java.util.List;

import fun.codedesign.principle.advice151.Bad;
import fun.codedesign.principle.advice151.Good;
import fun.codedesign.principle.advice151.Notice;

/**
 * 对象数组转换异常 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-05 20:13
 * @since 1.0.0
 */
@Notice("数组无法直接进行类型转换，list有两个方式转变为数组，list.toArray和list.toArray(T[])")
public class ObjectArrayConvertError {

    @SuppressWarnings("all")
    @Bad("会报数组转换异常，比如String[]类型数组无法转换为Object[]")
    public static <T> T[] toArray(List<T> list) {
        if (list != null) {
            Object[] targetArray = new Object[list.size()];
            for (int i = 0, size = list.size(); i < size; i++) {
                targetArray[i] = list.get(i);
            }
            return (T[]) targetArray;
        } else {
            return null;
        }
    }

    @SuppressWarnings("all")
    @Good("指定了数组元素的类型，然后创建该类型数组就可以解决该问题了")
    public static <T> T[] toArray(List<T> list, Class<T> clazz) {
        if (list == null || list.size() == 0) return null;
        T[] ts = (T[]) Array.newInstance(clazz, list.size());
        for (int i = 0, size = list.size(); i < size; i++) {
            ts[i] = list.get(i);
        }
        return ts;
    }
}
